package persistencia;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class Conexion {
	private boolean connected;
	private Connection connection;
	private String driver, bdURL, user, pwd;
	
	public Conexion(){
		this.driver="com.mysql.jdbc.Driver";
		this.bdURL="jdbc:mysql://localhost/CASINOBD?";
		this.user="jorge";
		this.pwd="1234";
		this.connection=null;
		this.connected=false;
	}
	
	public void connect() throws SQLException {
		try {
			if(!connected){
				try {
					Class.forName(driver);
				} catch (ClassNotFoundException e) {
					System.err.println("ERROR: no se ha encontrado el driver de mysql."
										+ " Ponlo bien!!!\n" + e.toString());
				}
				connection = DriverManager.getConnection(bdURL,user,pwd);
				if (connection != null && connection.isValid(0)) {
	                System.out.println("Conectado a la base de datos");
	                connected=true;
	            }
			}

		} catch (SQLException e) {
			throw e;
		}
	}
	
	public void disconnect() throws SQLException{
		try{
			if(connected && connection!=null && !connection.isClosed()){
				connection.close();
				if (connection.isClosed()) {
	                System.out.println("Conexion correctamente cerrada");
	            }
			}
		}catch(SQLException e){
			throw e;
		}
	}
	
	public void update(String query) throws SQLException {
		try {
			if (connected) {
				Statement st = connection.createStatement();
				st.executeUpdate(query);
			}
		} catch (SQLException e) {
			throw e;
		}
	}

	public ResultSet execute(String query) throws SQLException {
		ResultSet res = null;
		try {
			if (connected) {
				Statement st = connection.createStatement();
				res = st.executeQuery(query);
			}
		} catch (SQLException e) {
			throw e;
		}
		return res;
	}

}
